package org.jeecg.modules.demo.soSaleOrder.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.api.dto.message.TemplateMessageDTO;
import org.jeecg.common.system.api.ISysBaseAPI;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.modules.demo.cwSaleInvoice.entity.CwSaleInvoice;
import org.jeecg.modules.demo.cwSaleInvoice.mapper.CwSaleInvoiceMapper;
import org.jeecg.modules.demo.soSaleOrder.entity.SoSaleOrder;
import org.jeecg.modules.demo.soSaleOrder.mapper.SoSaleOrderMapper;
import org.jeecg.modules.demo.soSaleOrder.service.ISoSaleOrderService;
import org.jeecg.modules.demo.soSettlement.entity.SoSettlement;
import org.jeecg.modules.demo.soSettlement.entity.SoSettlementVo;
import org.jeecg.modules.demo.soSettlement.mapper.SoSettlementMapper;
import org.jeecg.modules.demo.utils.generateOddUtil;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Description: so_sale_order
 * @Author: jeecg-boot
 * @Date:   2021-12-06
 * @Version: V1.0
 */
@Service
public class SoSaleOrderServiceImpl extends ServiceImpl<SoSaleOrderMapper, SoSaleOrder> implements ISoSaleOrderService {

    @Resource
    private SoSaleOrderMapper soSaleOrderMapper;
    @Resource
    private CwSaleInvoiceMapper cwSaleInvoiceMapper;
    @Resource
    private SoSettlementMapper soSettlementMapper;
    @Resource
    private ISysBaseAPI sysBaseAPI;

    private String getMessage(String name,String date) {
        String str ="由【"+name+"】于【"+date+"】发起的销售发票单需要您的审核，请及时查看！";
        return str;
    }
    private static final String TITLE = "单据审核";

    @Override
    public SoSaleOrder getBysoNo(String soOrder) {
        return soSaleOrderMapper.getBysoNo(soOrder);
    }

    @Override
    public List<SoSaleOrder> getSoOrderList(String parameter){
        return soSaleOrderMapper.getSoOrderList(parameter);
    }

    @Override
    public String getTname(String tenantId) {
        return soSaleOrderMapper.getTname(tenantId);
    }

    @Override
    public Map<String,Double>  getXSOrderQuantity(String beginTime,String endTime){
        return soSaleOrderMapper.getXSOrderQuantity(beginTime,endTime);
    }
    @Override
    public Map<String,Double>  getXSQualityIQ(String beginTime,String endTime){
        return soSaleOrderMapper.getXSQualityIQ(beginTime,endTime);
    }
    @Override
    public Map<String,Double>  getXSSettlementVolume(String beginTime,String endTime){
        return soSaleOrderMapper.getXSSettlementVolume(beginTime,endTime);
    }
    @Override
    public Map<String,Double>  getXSInvoiceQuantity(String beginTime,String endTime){
        return soSaleOrderMapper.getXSInvoiceQuantity(beginTime,endTime);
    }

    @Override
    public List<SoSettlementVo> queryYingshou() {
        return soSaleOrderMapper.queryYingshou();
    }

    @Override
    public SoSettlementVo queryYingshou1() {
        return soSaleOrderMapper.queryYingshou1();
    }

    @Override
    public List<SoSettlementVo> queryYingfu() {
        return soSaleOrderMapper.queryYingfu();
    }

    @Override
    public SoSettlementVo queryYingfu1() {
        return soSaleOrderMapper.queryYingfu1();
    }


    @Override
    @Transactional
    public boolean addSoInvoice(JSONObject jsonObject, HttpServletRequest req) {
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        try {
            SoSaleOrder sso = JSON.parseObject(jsonObject.toJSONString(), SoSaleOrder.class);
            CwSaleInvoice csi = JSON.parseObject(jsonObject.toJSONString(), CwSaleInvoice.class);
            String max_code = cwSaleInvoiceMapper.getMaxCode();
            Map<String,String> codeMap = new HashMap<>();
            if(max_code == null){
                codeMap.put("maxCode",null);
            }else{
                codeMap.put("maxCode",max_code);
            }
            String tenantId = req.getHeader("tenant-id");
            String tname = soSaleOrderMapper.getTname(tenantId);
            String name =tname+ "FP_";

            String resultCode = generateOddUtil.createCode(codeMap,name);
            csi.setId("");
            csi.setInvoiceNo(resultCode);
            csi.setSoNo(sso.getSoOrder());
            csi.setPrdName(sso.getPrdNo());
            csi.setIsDelete(0);
            csi.setIsSkd(0);
            csi.setSoStatus(0);
            csi.setFplx("4");
            csi.setSupamount(csi.getSkJine());
            csi.setKkpJine(csi.getSkJine());
            csi.setSoCustom(sso.getSoCustom());
            csi.setPrdName(sso.getPrdNo());
            csi.setHsdj(sso.getHsdj());
            csi.setHsje(sso.getHsdj().multiply(csi.getFpsl()));
            csi.setWsdj(sso.getWsdj());
            csi.setWsje(sso.getWsdj().multiply(csi.getFpsl()));
            csi.setPsTax(csi.getHsje().subtract(csi.getWsje()));
            csi.setRealzb(sso.getTarget());
            csi.setCreateTime(new Date());
            if (csi.getScCdate() == null){
                csi.setScCdate(new Date());
            }
            csi.setCreateTime(new Date());
            cwSaleInvoiceMapper.insert(csi);

            LoginUser user = sysBaseAPI.getUserById(csi.getPoStaff());
            TemplateMessageDTO templateMessageDTO = new TemplateMessageDTO();
            templateMessageDTO.setFromUser("管理员");
            templateMessageDTO.setToUser(csi.getShName()+",");
            templateMessageDTO.setTitle(TITLE);
            templateMessageDTO.setTemplateCode("order");
            Map<String, String> templateParam = new HashMap<>();
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String date= simpleDateFormat.format(new Date());
            templateParam.put("ts_date",date);
            templateParam.put("ts_content", getMessage(user != null?user.getRealname():"该业务员不存在！", date));
            templateParam.put("checkOrder",csi.getInvoiceNo());
            templateParam.put("cd_url","/collection/CwSaleInvoiceList");
            templateMessageDTO.setTemplateParam(templateParam);
            sysBaseAPI.sendTemplateAnnouncement(templateMessageDTO);

            SoSaleOrder ss = soSaleOrderMapper.getBysoNo(sso.getSoOrder());
            if (ss.getKpJine() == null) {
                ss.setKpJine(csi.getSkJine());
            } else {
                ss.setKpJine(ss.getKpJine().add(csi.getSkJine()));
            }
            if (ss.getKpNum() == null) {
                ss.setKpNum(csi.getFpsl());
            } else {
                ss.setKpNum(ss.getKpNum().add(csi.getFpsl()));
            }
            if (ss.getKjskpNum() == null){
                ss.setKjskpNum(csi.getFpsl());
            }else {
                ss.setKjskpNum(ss.getKjskpNum().add(csi.getFpsl()));
            }
            if (ss.getKjsJine() == null){
                ss.setKjsJine(csi.getSkJine());
            }else {
                ss.setKjsJine(ss.getKjsJine().add(csi.getSkJine()));
            }
            if (ss.getKpNum().compareTo(ss.getSoTotail()) > -1 || ss.getKpJine().compareTo(ss.getHsje()) > -1) {
                ss.setIsYkp(1);
            }
            soSaleOrderMapper.updateById(ss);

            String str= soSettlementMapper.getMaxCode();
            Map<String,String> map = new HashMap<>();
            if(str==null){
                map.put("maxCode",null);
            }else{
                map.put("maxCode",str);
            }
            String jsname =tname+ "JS_";
            String xsjs = generateOddUtil.createCode(map,jsname);


            SoSettlement soSettlement = new SoSettlement();
            soSettlement.setId("");
//            soSettlement.setSoqNo(sqo.getQoNum());


            soSettlement.setSosNo(xsjs);
            soSettlement.setSosTotal(csi.getFpsl());
            soSettlement.setSosCdate(new Date());
            soSettlement.setSosStaff(sysUser.getRealname());
            soSettlement.setIsDelete(0);
            soSettlement.setIsFpd(0);
            soSettlement.setSoStatus(0);
            soSettlement.setSoNo(sso.getSoOrder());
            soSettlement.setPrdName(csi.getPrdName());
            soSettlement.setDept(csi.getDept());
            soSettlement.setSoCustom(csi.getSoCustom());
//            soSettlement.setSosNum(csi.getFpsl());
            soSettlement.setProject(csi.getProject());
            soSettlement.setCreateTime(new Date());
            soSettlement.setSosPrice(csi.getHsdj());
            soSettlement.setHtjjia(soSettlement.getWsdj());
            soSettlement.setWkpJine(csi.getSkJine());
            soSettlement.setSosAmount(csi.getSkJine());
            soSettlement.setPsTax(csi.getPsTax());
            soSettlement.setHsdj(csi.getHsdj());
            soSettlement.setWsdj(csi.getWsdj());
            soSettlement.setHsje(csi.getHsje());
            soSettlement.setWsje(csi.getWsje());
            soSettlement.setJsType(2);
            soSettlement.setKjsJine(csi.getSkJine());
            soSettlement.setKjsNum(csi.getFpsl());
            soSettlement.setSoStatus(1);
            soSettlement.setIsFpd(1);
            soSettlement.setTradecode(csi.getTradecode());
            soSettlementMapper.insert(soSettlement);


            csi.setSosNo(soSettlement.getSosNo());
            cwSaleInvoiceMapper.updateById(csi);

            return true;
        } catch (Exception e) {
            e.printStackTrace();
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return false;
        }
    }

    @Override
    public Date getTdate(String tenantId) {
        return soSaleOrderMapper.getTdate(tenantId);
    }


    @Override
    public String getMaxCode(){
        return soSaleOrderMapper.getMaxCode();
    }
    @Override
    public SoSaleOrder getBySodHetbh(String mainId) {
        return soSaleOrderMapper.getBySodHetbh(mainId);
    }
}
